<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageOrdersAddress;
use plugin\ycMassage\app\model\MassageOrdersTransferring;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianBill;
use plugin\ycMassage\app\model\MassageUserTechnicianScheduling;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\ServiceState;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use think\facade\Db;
use think\Request;

class OrdersTransferringController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->checkboxConfig();
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('trade', 'input', '订单号');
        $builder->addScreen('name', 'input', '下单人');
        $builder->addScreen('mobile', 'input', '下单手机号');
        $builder->addScreen('technician', 'input', '技师');
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);
        $builder->addScreen('start_time', 'input', '开始时间', [
            'type' => 'date'
        ]);
        $builder->addScreen('end_time', 'input', '结束时间', [
            'type' => 'date'
        ]);
        $builder->addRightButton('handle', '转单', [
            'api'    => $this->pluginPrefix . '/admin/OrdersTransferring/handle',
            'path' => '/OrdersTransferring/handle',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::WAIT['value']
            ],
            'aliasParams' => [
                'orders_id' => 'orders_id'
            ],
        ], [
            'customStyle'=>[
                'width'=>'1140px',
                'minHeight'=>'800px'
            ]
        ], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('reject', '驳回', [
            'api'    => $this->pluginPrefix . '/admin/OrdersTransferring/reject',
            'type'      => 'confirm',
            'method' => 'post',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::WAIT['value']
            ],
        ], [
            'title'   => '温馨提示',
            'content' => '确定要驳回吗？',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('title', '服务项目详情', [
                'minWidth' => 200,
            ])
            ->addColumn('name', '下单人', [
                'width' => 160,
            ])
            ->addColumn('mobile', '下单手机号', [
                'width' => 160,
            ])
            ->addColumn('old_technician_nickname', '原技师', [
                'width' => 160,
            ])
            ->addColumn('technician_nickname', '技师', [
                'width' => 160,
            ])
            ->addColumn('trade', '订单号', [
                'minWidth' => 200,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => OrdersState::dictOptions(),
                    'style' => OrdersState::dictOptions('style'),
                ],
            ])
            ->addColumn('remark', '备注', [
                'width' => 160,
            ])
            ->addColumn('create_time', '下单时间', [
                'width' => 160,
            ])
            ->addColumnEle('examine', '审核', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('transferring_message', '转单理由', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['o.saas_appid', '=', $request->saas_appid]
        ];
        $trade = $request->get('trade');
        if ($trade) {
            $where[] = ['o.trade', 'like', '%' . $trade . '%'];
        }
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['o.uid', '=', $uid];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['r.examine', '=', $examine];
        }
        $start_time = $request->get('start_time');
        if ($start_time) {
            $where[] = ['o.create_time', '>=', $start_time . ' 00:00:00'];
        }
        $end_time = $request->get('end_time');
        if ($end_time) {
            $where[] = ['o.create_time', '<=', $end_time . ' 23:59:59'];
        }
        $where[] = ['r.use_role', '=', ActionIdentity::TECHNICIAN['value']];
        $filed = [
            'o.title,o.origin_price,o.price as orders_price,o.basic_price,o.overtime_price,o.travel_price,o.material_price,o.coupon_money,o.num,o.trade,o.pay_type,o.pay_time,o.state,o.remark,o.create_time',
            'r.id,r.orders_id,r.transferring_message,r.examine,r.create_time as refund_time',
        ];
        $MassageOrdersObj = MassageOrdersTransferring::alias('r')->where($where);
        $MassageOrdersObj->join('massage_orders o', 'o.id = r.orders_id');
        $filed[] = 'address.name,address.mobile';
        $filed[] = 'ut.nickname as technician_nickname';
        $filed[] = 'old_ut.nickname as old_technician_nickname';
        $technician = $request->get('technician');
        if ($technician) {
            $where[] = ['ut.realname|t.mobile', 'like', "%{$technician}%"];
            $MassageOrdersObj->join('MassageUserTechnician t', 't.uid=o.alias_id');
        }
        $MassageOrdersObj->join('MassageUser ut', 'ut.id=o.alias_id');
        $MassageOrdersObj->join('MassageUser old_ut', 'old_ut.id=r.technician_id','left');
        $name = $request->get('name');
        if ($name) {
            $where[] = ['address.name', 'like', "%{$name}%"];
        }
        $mobile = $request->get('mobile');
        if ($mobile) {
            $where[] = ['address.mobile', 'like', "%{$mobile}%"];
        }
        $MassageOrdersObj->join('MassageOrdersAddress address', 'address.orders_id = o.id');
        $data = $MassageOrdersObj->order('r.id desc')
            ->field($filed)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->technician_nickname) {
                    $item->technician_nickname = base64_decode($item->technician_nickname);
                }
                if ($item->old_technician_nickname) {
                    $item->old_technician_nickname = base64_decode($item->old_technician_nickname);
                }
            });
        return $this->successRes($data);
    }
    public function handle(Request $request)
    {
        $orders_id = $request->get('orders_id');
        $MassageOrders = MassageOrders::where(['id' => $orders_id])->find();
        if(!$MassageOrders){
            return $this->fail('数据不存在');
        }
        $MassageOrdersTransferring = MassageOrdersTransferring::where(['orders_id' => $MassageOrders->id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageOrdersTransferring) {
            return $this->fail('数据不存在');
        }
        $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageOrders->uid])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.nickname,u.headimg,u.mobile,uw.openid')
            ->find();
        $MassageUserT = MassageUser::alias('u')->where(['u.id' => $MassageOrders->alias_id])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.id,u.nickname,u.headimg,u.mobile,uw.openid')
            ->find();
        $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $MassageOrders->id])->find();
        $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $MassageOrdersTransferring->orders_id])->order('state desc')->find();
        if ($request->method() === 'POST') {
            $D = $request->post();
            if($D['technician_id']==$MassageOrders->alias_id){
                return $this->fail('不能转单给自己');
            }
            $start_time=$MassageAppointmentService->start_time;
            $st=strtotime($start_time);
            $his=date('H:i:s',$st);
            if($st<time()){
                $start_time=date('Y-m-d '.$his);
                $st=strtotime($start_time);
                if($st<time()){
                    $start_time=date('Y-m-d '.$his,strtotime('+1 day'));
                }
            }
            $MassageUserTechnician=MassageUserTechnician::where(['saas_appid' => $request->saas_appid, 'uid' => $D['technician_id']])->find();
            $MassageUserTechnicianScheduling=MassageUserTechnicianScheduling::where(['saas_appid' => $request->saas_appid,'uid'=>$MassageUserTechnician->uid])->whereTime('start_time', '<=', $start_time)
            ->whereTime('end_time', '>=', $start_time)->find();
            if(!$MassageUserTechnicianScheduling){
                return $this->fail("该技师在{$start_time}时间段没有排班");
            }
            $commuting_duration=$MassageAppointmentService->commuting_duration;
            $hasReservationState = MassageAppointmentService::hasReservation(
                $MassageUserTechnicianScheduling->id,
                $MassageUserTechnicianScheduling->start_time,
                $MassageUserTechnicianScheduling->end_time,
                $start_time,
                $MassageAppointmentService->duration + $commuting_duration
            );
            if (!$hasReservationState) {
                return $this->fail("{$start_time}服务时间已被预约，请重新选择");
            }
            $MassageOrdersTransferring->examine = Examine::YES['value'];
            Db::startTrans();
            try {
                $MassageOrders->alias_id=$MassageUserTechnician->uid;
                if($MassageUserTechnician->work_mch_id){
                    if(!$MassageUserTechnician->work_shop_id){
                        return $this->fail('技师需要先签约门店');
                    }
                    $MassageOrders->mch_id=$MassageUserTechnician->work_mch_id;
                    $MassageOrders->shop_id=$MassageUserTechnician->work_shop_id;
                }else{
                    $MassageOrders->mch_id=null;
                    $MassageOrders->shop_id=null;
                }
                $MassageOrders->state=OrdersState::WAIT_START['value'];
                $MassageOrders->save();
                $MassageOrdersSub=MassageOrdersSub::where(['orders_id'=>$MassageOrders->id])->select();
                foreach ($MassageOrdersSub as $item) {
                    $item->technician_id=$MassageUserTechnician->uid;
                    $item->save();
                }
                $travel_price=0;
                $remarks='';
                $MassageAppointmentService=MassageAppointmentService::where(['orders_id'=>$MassageOrders->id])->select();
                foreach ($MassageAppointmentService as $item) {
                    if($item->state===ServiceState::TRAVELING['value']&&$travel_price===0){
                        $travel_price=1;
                        $remarks = "转单扣除订单：{$MassageOrders->trade} - 去程路费";
                    }elseif($item->state===ServiceState::ARRIVAL['value']&&$travel_price===1){
                        $travel_price=2;
                        $remarks = "转单扣除订单：{$MassageOrders->trade} - 往返路费";
                    }
                    $item->technician_id=$MassageUserTechnician->uid;
                    $item->scheduling_id=$MassageUserTechnicianScheduling->id;
                    if($MassageOrders->shop_id){
                        $item->mch_id=$MassageOrders->mch_id;
                        $item->shop_id=$MassageOrders->shop_id;
                    }
                    $item->state=ServiceState::WAIT_START['value'];
                    $item->start_time=$start_time;
                    $item->departure_time=null;
                    $item->arrival_time=null;
                    $item->service_start_time=null;
                    $item->service_end_time=null;
                    $item->verification=State::NO['value'];
                    $item->verification_time=null;
                    $item->save();
                }
                if($travel_price&&$MassageOrders->travel_price > 0){
                    $travel_price=($MassageOrders->travel_price/2)*$travel_price;
                    MassageUserTechnicianBill::decrease($remarks, $MassageUserT->id, $travel_price);
                }
                $MassageOrdersTransferring->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            $notice = new Notice();
            if ($MassageUser) {
                $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
            }
            if ($MassageUserT) {
                $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
            }
            $notice->saas_appid = $MassageOrders->saas_appid;
            $notice->type = NoticeType::TRANSFERRING['value'];
            $notice->setData([
                'trade' => $MassageOrders->trade,
                'state' => '转单成功',
                'time' => date('Y-m-d H:i:s',strtotime($start_time."-{$commuting_duration} minutes")),
                'name' => $MassageOrdersAddress['name'] . '(' . $MassageOrders->uid . ')',
            ]);
            $notice->send();
            return $this->success('转单成功');
        }
        $TechnicianState = [
            'type' => 'error',
            'text' => ServiceState::getText($MassageOrdersTransferring->service_state)['text']
        ];
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addDivider('当前服务技师和客户');
        $builder->addComponent('headimgT', 'el-avatar', '技师头像', '', [
            'col'           => 4,
            'props'         => [
                'size'     => 50,
                'shape' => 'square',
                'src'      => $MassageUserT->headimg,
            ],
        ]);
        $builder->addComponent('nicknameT', 'info', '技师昵称', $MassageUserT->nickname, [
            'col'           => 4,
            'props'         => []
        ]);
        $builder->addComponent('realnameT', 'info', '技师姓名', $MassageUserT->realname, [
            'col'           => 4,
            'props'         => []
        ]);
        $builder->addComponent('headimg', 'el-avatar', '客户头像', '', [
            'col'           => 4,
            'props'         => [
                'size'     => 50,
                'shape' => 'square',
                'src'      => $MassageUser->headimg,
            ],
        ]);
        $builder->addComponent('nickname', 'info', '客户昵称', $MassageUser->nickname, [
            'col'           => 4,
            'props'         => []
        ]);
        $builder->addComponent('realname', 'info', '客户', $MassageOrdersAddress->name, [
            'col'           => 4,
            'props'         => []
        ]);
        $builder->addDivider('服务');
        $builder->addComponent('TechnicianState', 'el-tag', '服务状态', '', [
            'col'           => 6,
            'props'         => [
                'type'      => $TechnicianState['type']
            ],
            'children'      => [
                $TechnicianState['text']
            ]
        ]);
        $builder->addComponent('price', 'el-tag', '订单金额', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'success'
            ],
            'children'      => [
                "￥{$MassageOrders->price}"
            ]
        ]);
        $builder->addComponent('travel_price', 'el-tag', '路费', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'success'
            ],
            'children'      => [
                "￥{$MassageOrders->travel_price}"
            ]
        ]);
        $builder->addComponent('start_time', 'info', '预约时间', $MassageAppointmentService->start_time, [
            'col'           => 6
        ]);
        $builder->addDivider('项目');
        $MassageOrdersSub = MassageOrdersSub::alias('os')->where(['os.orders_id' => $MassageOrdersTransferring->orders_id])
            ->join('MassageService s', 's.id = os.service_id')
            ->field('os.*,s.title,s.thumb')
            ->select()->each(function ($item) {
                $item->thumb = UploadService::url($item->thumb);
            });
        foreach ($MassageOrdersSub as $item) {
            $builder->addComponent('url' . $item->id, 'el-avatar', '封面', '', [
                'col'           => 4,
                'props'         => [
                    'size'     => 50,
                    'shape' => 'square',
                    'src'      => $item->thumb,
                ],
            ]);
            $builder->addComponent('title' . $item->id, 'info', '服务项目', "{$item->title} x {$item->num}", [
                'col'           => 14,
                'props'         => []
            ]);
            $builder->addComponent('price' . $item->id, 'el-tag', '金额', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => 'success'
                ],
                'children'      => [
                    "￥{$item->price}"
                ]
            ]);
        }
        $builder->addComponent('technician_id', 'remote', '选择一个转单技师', '', [
            'col'           => 24,
            'props'         => [
                'file' => "app/ycMassage/remote/form/search-technician",
                'orders_id' => $MassageOrders->id
            ]
        ]);
        $data = $builder->setData($MassageOrdersTransferring)->create();
        return $this->successRes($data);
    }
    public function reject(Request $request)
    {
        $id=$request->post('id');
        $MassageOrdersTransferring = MassageOrdersTransferring::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        Db::startTrans();
        try {
            $MassageOrdersTransferring->examine = Examine::NO['value'];
            $MassageOrdersTransferring->save();
            $MassageOrders=MassageOrders::where(['id'=>$MassageOrdersTransferring->orders_id])->find();
            $MassageOrders->state=$MassageOrdersTransferring->orders_state;
            $MassageOrders->save();
            $MassageAppointmentService=MassageAppointmentService::where(['orders_id'=>$MassageOrders->id])->select();
            foreach ($MassageAppointmentService as $item) {
                $item->state=$MassageOrdersTransferring->service_state;
                $item->save();
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $notice = new Notice();
        $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageOrders->uid])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.nickname,u.headimg,u.mobile,uw.openid')
            ->find();
        $MassageUserT = MassageUser::alias('u')->where(['u.id' => $MassageOrders->alias_id])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.id,u.nickname,u.headimg,u.mobile,uw.openid')
            ->find();
        if ($MassageUser) {
            $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
        }
        if ($MassageUserT) {
            $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
        }
        $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $MassageOrders->id])->find();
        $notice->saas_appid = $MassageOrders->saas_appid;
        $notice->type = NoticeType::TRANSFERRING['value'];
        $notice->setData([
            'trade' => $MassageOrders->trade,
            'state' => '转单失败',
            'time' => date('Y-m-d H:i:s'),
            'name' => $MassageOrdersAddress['name'] . '(' . $MassageOrders->uid . ')',
        ]);
        $notice->send();
        return $this->success('操作成功');
    }
}
